package com.lang.progress;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 下载进度处理器
 */
public class DProgress {

    /**
     * 名称
     */
    private final String name;
    /**
     * 下载文件总长度
     */
    private final Long contentLength;
    /**
     * 已经下载的长度
     */
    private final AtomicLong hasDone = new AtomicLong();
    /**
     * 每一次计算时调用的方法
     */
    private Set<DWhenCount> whenCountSet;

    public DProgress(String name, Long contentLength) {
        this.name = name;
        this.contentLength = contentLength;
    }

    /**
     * 添加每次计算触发的方法
     *
     * @param whenCount 每次计算触发的方法
     */
    public void addWhenCount(DWhenCount whenCount) {
        if (whenCount == null)
            return;
        if (whenCountSet == null)
            whenCountSet = new HashSet<>();
        whenCountSet.add(whenCount);
    }

    /**
     * 计数
     *
     * @param countLength 此次计数大小
     */
    public void count(long countLength) {
        boolean isCompleted = (hasDone.addAndGet(countLength) == contentLength);
        for (DWhenCount whenCount : whenCountSet) {
            whenCount.whenCount(name, countLength, hasDone, contentLength, isCompleted);
        }
    }

    /**
     * @return 是否已完成
     */
    public boolean isDone() {
        return hasDone.get() == contentLength;
    }
}
